__version__ = "1.1.0"

import datetime



from django.http import JsonResponse
from typing import Optional, Dict, Any

from django.utils import timezone
import logging
from Tools.logtools.logtools import logfile_hander, console_handler
logger = logging.getLogger(__name__)
logger.setLevel(level=logging.INFO)
logger.addHandler(logfile_hander())
logger.addHandler(console_handler())

class ApiResponse:
    def __init__(self, code: int = 0, message: str = "success", count:int = 0 ,data: Optional[Dict[str, Any]] = None):
        self.code = code
        self.message = message
        self.count = count
        self.data = data or {} or list

    def to_json(self):
        """转换为Django JsonResponse（带时区处理）"""
        logger.info(f"API响应: {self.code} - {self.message}")

        # 基础响应结构
        response = {
            "code": self.code,
            "message": self.message
        }

        # 添加数据字段
        if self.data is not None:
            response["data"] = self.data

        # 条件性添加 count 字段
        if self.count is not None:
            response["count"] = self.count

        # 自动转换datetime对象为ISO格式字符串
        def date_handler(obj):
            if isinstance(obj, (datetime.date, datetime.datetime)):
                return timezone.localtime(obj).isoformat()
            return None

        return JsonResponse(
            response,
            status=200,
            json_dumps_params={'default': date_handler}
        )


    @staticmethod
    def success(data=None, message="操作成功"):
        return JsonResponse({
            'code': 0,
            'message': message,
            'data': data
        }, status=200)

    @staticmethod
    def created(data):
        return JsonResponse({
            'code': 201,
            'message': '资源已创建',
            'data': data
        }, status=201)

    @staticmethod
    def error(code=400, message="请求错误"):
        return JsonResponse({
            'code': code,
            'message': message
        }, status=code)
